import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Start this program,then "telnet localhost 8083 " to connect it
 * @author cjf
 *
 */
public class ChannelAccept {
	
	public static final String GREETING = "Hello,welcome connect the server! I'm going ! \r\n";
	
	public static void main(String[] args) throws IOException, InterruptedException {
		
		int port = 8083;
		if(args.length > 0){
			port = Integer.parseInt(args[0]);
		}
		
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		ServerSocket socket = serverSocketChannel.socket();
		socket.bind(new InetSocketAddress(port));
		serverSocketChannel.configureBlocking(false);
		
		ByteBuffer byteBuffer = ByteBuffer.wrap(GREETING.getBytes("UTF-8"));
		
		System.out.println("start listen:");
		while (true) {
			System.out.println("waitting for connections ……");
			SocketChannel sc = serverSocketChannel.accept();
			if(sc ==  null){
				Thread.sleep(2000);
			}else{
				System.out.println("Incomming connection from " + sc.socket().getRemoteSocketAddress());
				byteBuffer.rewind();
				sc.write(byteBuffer);
				sc.close();
			}
		}
		
	}
	

}
